﻿using Finance.Infrastructrue.Interface;
using Finance.API.Write.Application.Command.PayableManagementCommand;
using Finance.Domain;
using Finance.ErrorCode;
using MediatR;
using AutoMapper;
using System.DirectoryServices.Protocols;
using Finance.Infrastructrue.Implement;
using System.Transactions;
using Dapper;
using static Dm.net.buffer.ByteArrayBuffer;

namespace Finance.API.Write.Application.Hander.PayableManagementHander
{
    public class UpdPayableManagementHander:IRequestHandler<UpdPayableManagementCommand ,APIResult<int>>
    {
        DatabaseContext db;
        IBaseRepository<PayableManagement> payRep;
        ILogger<UpdPayableManagementHander> logger;
        IMapper mapper;

        public UpdPayableManagementHander(DatabaseContext db, IBaseRepository<PayableManagement> payRep, ILogger<UpdPayableManagementHander> logger, IMapper mapper)
        {
            this.db = db;
            this.payRep = payRep;
            this.logger = logger;
            this.mapper = mapper;
        }

        public  async Task<APIResult<int>> Handle(UpdPayableManagementCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            try
            {
                
                    //查询该生产编号是否存在
                    var mls = db.SqlSugar.Queryable<PayableManagement>().Count(a => !a.IsDel && a.FlowingWaterNumber == request.FlowingWaterNumber);

                    if (mls > 1)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "该编号已存在";
                        return await Task.FromResult(result);
                    }
                    
                    var payable = mapper.Map<PayableManagement>(request);
                    payable.IsDel = false;
                //用来解决修改的
                //payable.State = 0;
               
                if (request.rid ==2)//0是未审核，1是审核成功，2是审核失败
                {
                  
                        //找到统一的生产编号
                        var Node = db.SqlSugar.Queryable<PayableManagement>().Where(a => a.FlowingWaterNumber.Contains(payable.FlowingWaterNumber)).First();
                      

                        //财务记账
                        FinancialBookkeeping financial = new FinancialBookkeeping()
                        {
                            FlowingWaterNumber = payable.FlowingWaterNumber,
                            FinancialBookkeepingName = payable.PayableManagementName,
                            FinancialBookkeepingType = Node.PayableManagementType,
                            BeneficiaryOrPayer = payable.Recipients,
                            PaymentAmount = payable.PaidInAmount,
                            PaymentStype = payable.PayableManagementType,
                            Type = "应付",
                            PaymentTime = DateTime.Now,
                            PaymentInstitutions = payable.PaymentInstitutions,
                            CreatTime = payable.CreatTime,
                            CreatName = payable.CreatName,
                            UpdateTime = payable.UpdateTime,
                            UpdateName = payable.UpdateName,
                            DeleteTime = payable.DeleteTime,
                            DeleteName = payable.DeleteName,
                            IsDel = payable.IsDel
                        };
                        await db.SqlSugar.Insertable(financial).ExecuteCommandAsync();
                        // payable.State = Node.State;
                    }
                
               

                var m = await db.SqlSugar.Updateable(payable).ExecuteCommandAsync();

                  


                    if (m > 0)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "应付管理修改成功";
                        result.Data = m;
                    }
                    else
                    {
                        result.Code = APIEnum.Fail;
                        result.Message = "应付管理修改失败";
                        result.Data = m;
                    }
                
            }
            catch (Exception ex)
            {
                
                logger.LogError("应付管理修改报错" + ex.Message);
                throw;
            }

            return await Task.FromResult(result);
        }       
    }
}
